import React, { useState, useEffect } from 'react';
import { Button, Col, Divider, Select, Space, Spin } from 'antd';
import _ from 'lodash';

import { TRMessage } from '#/components';
import { DownSquareOutlined, UploadOutlined, UpSquareOutlined } from '#/utils/antdIcons';
import { useTRState } from '#/utils/trHooks';
import { default as TreeTable } from '../Main/PXBMX/table';

import { TjChart, TjSegmented } from '@/pages/ETrade/components';
import { export_json_sheets_to_excel, export_json_to_excel } from '@/utils/fileExport';

import { default as HeadForm } from './form';
import { default as ChartSon } from './detail';
import {
  getHistoryMarketRunDataList,
  getHistoryMarketSpotPrice,
  getLongTermDataDashboard,
  getMengxiMarketSupplyDemandLongTermDataForecastData,
} from './sercives';
import {
  exportHelpr,
  getChartOption,
  GS_MODS,
  handleExportDataMengXi,
  handleRenderData,
  MODS,
} from './helper';
import styles from './index.less';
import { getPassageNameListNew } from '../Main/services';
import { PageLoading } from '@/components';
import { ChartTitle } from '@/pages/ETrade/OperatingDataDisclosure/MarketSupplyData/Main/components';

// 长周期数据看板
export default ({ power, buttonPermissions, market }) => {
  const [state, setState] = useTRState({
    // 重要通道实际输电情况
    passageName: '',
    operation: [],
    myMods: _.cloneDeep(MODS),
    //  记录使用过的表单
    formValue: null,
    stationId: null,
    stationName: '',
    stations: [], // 场站列表
    marketName: '', // 交易中心名称
    subTitle: '',
    // result
    dayRange: [], // 已选时间范围（后端按维度计算返回的）
    dataSource: {}, // 原始数据
    loading: true,
    loadingSpot: false,
    market: {},
  });

  async function onFetchOperation(params = {}) {
    // 其他数据
    setState({ loading: true });
    const res = await getPassageNameListNew(params);
    const operation = Object.entries(res?.data || {}).map((t) => ({ label: t[0], value: t[1] }));
    setState({
      operation,
      passageName: operation?.[0]?.value,
      loading: false,
    });
  }

  const onFetch = async (values, { market, stations, subTitle, dayRange }) => {
    // 取当前场站、切换交易中心下的第一个场站
    let stationId = state.stationId;
    let stationName = state.stationName;
    if (market?.value !== state.formValue?.marketId) {
      // 场站变化，默认取第一个
      stationId = stations?.[0]?.value || null;
      stationName = stations?.[0].label || '';
    }
    const marketName = market.label;
    state.myMods.map((x) => {
      x.expanded = false;
    });
    setState({
      stationId,
      stationName,
      stations,
      marketName,
      market,
      subTitle,
      loading: true,
      formValue: { ...values },
      myMods: _.cloneDeep(MODS),
    });
    // 交易中心为甘肃时
    if (values?.provinceId === '62') {
      const res = await getLongTermDataDashboard(values);
      await onFetchOperation(values);
      const dataSource = res?.resultMap || {};
      setState({
        dayRange,
        dataSource,
        loading: false,
        myMods: GS_MODS(dataSource),
      });
      return;
    }
    // 交易中心为蒙西时
    if (values?.provinceId === '15') {
      values.pointType = values.dayMonthPoint ? values.dayMonthPoint : 0;
      delete values.dayMonthPoint;
      getMengxiMarketSupplyDemandLongTermDataForecastData(values).then((res) => {
        const charts = handleRenderData(res?.data);
        setState({
          dayRange,
          dataSource: res?.data || [],
          charts,
          loading: false,
        });
      });
      return;
    }
    const [res1, res2] = await Promise.all([
      getHistoryMarketSpotPrice({ ...values, stationId }),
      getHistoryMarketRunDataList(values),
    ]);
    const dataSource = {
      ...(res1?.resultMap || {}),
      ...(res2?.resultMap || {}),
    };
    setState({
      dayRange,
      dataSource,
      loading: false,
    });
  };

  const changeStation = async (v, opt) => {
    const stationId = v;
    const stationName = opt?.label || '';
    setState({
      stationId,
      stationName,
      loadingSpot: true,
    });
    const res = await getHistoryMarketSpotPrice({
      ...state.formValue,
      stationId,
    });
    const dataSource = {
      ...state.dataSource,
      ...(res?.resultMap || {}),
    };
    setState({
      dataSource,
      loadingSpot: false,
    });
  };

  const _onExport = () => {
    // 导出
    const key = 'LongTermDataShowBoardButtonWeb';
    const canExport = buttonPermissions.some((x) => x.menuCode === key);
    if (!canExport) return TRMessage.info('请联系管理员获取相关权限');
    if (state.market.value === 'PXBMX') {
      // 蒙西导出
      const params = {
        header: [],
        data: [],
        filename: `省内现货披露-长周期数据看板-${state.marketName}`,
      };
      const exportDatas = [...handleExportDataMengXi(state.charts, state.dataSource)];
      export_json_to_excel(params, exportDatas);
      return;
    }
    const expParams = {
      type: 'xlsx',
      name: `省内现货披露-长周期数据看板-${state.marketName}`,
      list: exportHelpr(state.dataSource, {
        subTitle: state.subTitle,
        stationName: state.stationName,
        provinceId: state.formValue?.provinceId === '62',
      }),
    };
    export_json_sheets_to_excel(expParams);
  };

  const onChangeOperation = (v) => {
    // 通道切换
    setState({
      passageName: v,
    });
  };

  /** renders */
  const _renderMods = () => {
    if (state.loading) {
      return <PageLoading />;
    }
    if (state.market.value === 'PXBMX') {
      return state.charts.map((item) => {
        const right = (
          <Space size={16} wrap>
            <TjSegmented
              value={item.showTable || 0}
              options={[
                { label: '曲线', value: 0 },
                { label: '表格', value: 1 },
              ]}
              onChange={() => {
                item.showTable = Number(!item.showTable);
                setState({ charts: state.charts });
              }}
            />
          </Space>
        );

        const _columns = item?.columns || [];
        const _tableData = !!item.select
          ? item?.tableData?.[item.select] || []
          : item?.tableData || [];
        return (
          <Col span={item.span} key={'long' + item.id}>
            <div className={styles.box}>
              <ChartTitle name={item.name || ''} unit={item.unit || ''} right={right} />
              <div style={{ height: 240 }}>
                {item.showTable ? (
                  <div className={styles.tableWrap}>
                    ][=-
                    <TreeTable columns={_columns} dataSource={_tableData} />
                  </div>
                ) : (
                  <TjChart option={item.chartOption || null} group={'long' + item.group || ''} />
                )}
              </div>
            </div>
          </Col>
        );
      });
    }
    return state.myMods.map((item, i) => {
      const isSpot = item.datakey === 'spotPrice';
      const isImportAisle = item.datakey === 'operationRealtimePowerFlow';
      const itemData = state.dataSource?.[item?.datakey] || null;
      const itemOption = getChartOption(
        itemData,
        item,
        state.formValue?.provinceId,
        state.passageName,
      );
      return (
        <Spin spinning={isSpot && state.loadingSpot} key={item.datakey}>
          <div>
            <div>{i > 0 && <Divider style={{ margin: '16px 0' }} />}</div>
            <div>
              <div className={styles.chartHead}>
                <div className={styles.title}>
                  {item.name}
                  <span className={styles.titleSub}>{state.subTitle}</span>
                  <span className={styles.unit}>{item.unit}</span>
                </div>
                <Space size={16}>
                  {
                    // 重要通道实际输电情况
                    isImportAisle && (
                      <Space size={16}>
                        <Select
                          style={{ width: 200 }}
                          value={state.passageName}
                          options={state.operation}
                          optionFilterProp="label"
                          showSearch
                          showArrow
                          onChange={onChangeOperation}
                          getPopupContainer={(e) => e.parentNode}
                        />
                      </Space>
                    )
                  }
                  {isSpot && (
                    <Select
                      style={{ width: 200 }}
                      value={state.stationId}
                      options={state.stations}
                      optionFilterProp="label"
                      showSearch
                      showArrow
                      onChange={changeStation}
                      getPopupContainer={(e) => e.parentNode}
                    />
                  )}
                  <Button
                    disabled={state.formValue?.dayMonthPoint === 2}
                    style={{ padding: 0 }}
                    type="link"
                    icon={item.expanded ? <UpSquareOutlined /> : <DownSquareOutlined />}
                    onClick={() => {
                      item.expanded = !item.expanded;
                      setState({ myMods: state.myMods });
                    }}
                  >
                    {item.expanded ? '收起' : '展开'}
                  </Button>
                </Space>
              </div>
              <TjChart group={'groupHistory'} option={itemOption} style={{ height: 300 }} />
            </div>
            {item.expanded && (
              <div className={styles.sonWrap}>
                <ChartSon
                  dayRange={state.dayRange}
                  info={item}
                  form={{
                    ...state.formValue,
                    stationId: isSpot ? state.stationId : null,
                  }}
                />
              </div>
            )}
          </div>
        </Spin>
      );
    });
  };
  return (
    <div className={styles.cont}>
      <div className={styles.head}>
        <HeadForm
          power={power}
          market={market}
          loading={state.loading || state.loadingSpot}
          onChange={onFetch}
          setIsRe={() => {
            setState({
              stationId: state.stations?.[0]?.value || null,
              stationName: state.stations?.[0]?.label || '',
            });
          }}
        />
        <Space>
          <Button
            style={{ padding: 0 }}
            type="link"
            icon={<UploadOutlined />}
            disabled={state.loading || state.loadingSpot}
            onClick={_onExport}
          >
            导出
          </Button>
        </Space>
      </div>
      <div className={styles.main}>{_renderMods()}</div>
    </div>
  );
};
